package com.mdtx.database.utils;




import com.mdtx.database.DataBaseDriver;

import java.sql.*;

/**
 * 数据库连接工具
 *
 * @author 猫啊
 * @create 2018-06-12 18:10
 **/
public class DataBaseHelper {

    /**
     * 连接数据库
     * @param db
     */
    public static Connection getConnection(DataBaseDriver db){
        Connection connection = null;
        try {
            Class.forName(db.getDriver());
            connection = DriverManager.getConnection(db.getUrl(),db.getDbInfo());

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return connection;
    }

    /**
     * 关闭连接
     */
    public static void releaseConn(Connection connection, Statement state, ResultSet rs) {

        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(state!=null){
            try {
                state.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }



    /**
     *读取数据表信息
     * @param catalog
     * @param schemaPattern
     * @param tableNamePattern
     * @param types
     * @return
     * @throws SQLException
     */
    public static ResultSet getTables(Connection connection,String catalog, String schemaPattern,
                                      String tableNamePattern, String types[]) throws SQLException {
        DatabaseMetaData metaData = connection.getMetaData();
        return metaData.getTables(catalog,schemaPattern,tableNamePattern,types);

    }

    /**
     * 读取数据库表结构信息
     * @param catalog
     * @param schemaPattern
     * @param tableNamePattern
     * @return
     * @throws SQLException
     */
    public static ResultSet getAllColumns(Connection connection,String catalog, String schemaPattern,
                                          String tableNamePattern,String columnNamePattern) throws SQLException{
        DatabaseMetaData metaData = connection.getMetaData();
        return metaData.getColumns(catalog,schemaPattern,tableNamePattern,columnNamePattern);
    }


    /**
     * 读取数据库表中的主键
     * @param catalog
     * @param schema
     * @param table
     * @return
     * @throws SQLException
     */
    public static ResultSet getPrimaryKeys(Connection connection,String catalog, String schema,
                                           String table) throws SQLException{
        DatabaseMetaData metaData = connection.getMetaData();
        return metaData.getPrimaryKeys(catalog,schema,table);
    }
}
